<?php
namespace app\mobile\controller;
use think\Controller;
use think\Db;
use think\Session;
    class Ajax extends Controller

    {
        public function _initialize() {
        Session::start();
        if(!session('user.user_id')){
            return json(array('statu'=>'error','msg'=>'参数错误'));
            exit();
        }
        
      }
    	
        //保存投票信息
        public function insert_votebaoming(){
            //判断活动是否已过期
            $item['fvote_key']=I('post.voteid');
            //$t_vote=M('vote');
            $voteres=M('vote')->where(array('fkey'=>$item['fvote_key']))->find();
            if(is_array($voteres)){
                if($voteres['fvote_statdate']>time()){
                    $result['error']='nostart';
                    $result['statu']='forbidden';
                    $result['msg']='活动尚未开始';
                    return json($result);
                    exit();
                }
                if($voteres['fvote_enddate']<time()){
                    $result['error']='over';
                    $result['statu']='forbidden';
                    $result['msg']='活动已经结束';
                    return json($result);
                    exit();
                }    
            }
            //判断是否是会员
            $is_reg=is_reg(session('user.user_id'));
            if($is_reg!='have_reg'){
                if($is_reg=="no_subsribe"){
                    $result['error']='no_subsribe';
                    $result['statu']='forbidden';
                    $result['msg']='亲，只有关注微信我们公众号并成为会员，才能报名哦！';
                }
                if($is_reg=="no_reg"){
                    $result['error']='no_reg';
                    $result['statu']='forbidden';
                    $result['msg']='亲，只有注册并成为会员，才能报名哦！';
                }
                return json($result);
                exit();
            }
            //判断是否参与过
            $fvip_key=session('user.user_id');
            $ree=M('vote_item')->where(array('fvip_key'=>$fvip_key,'fvote_key'=>$item['fvote_key']))->find();
            if(is_array($ree)){
                $result['statu']='forbidden';
                $result['msg']='您已经参与过';
                return json($result);
                exit();
            }

            $wxpic=I('post.wxpic/a');
            $action=I('post.action');
            if($action=='cdresse'){
                $imgs=$wxpic;
            }else{
                //定义图片保存的正式目录
                $imgPath =C('IMG_LOAD_PATH').'wxpic/'.date('ym',time()).'/';
                
                if(!file_exists($imgPath)){
                  mkdir($imgPath,0777,true);
                }
                foreach ($wxpic as $key => $value) {
                     $fileName = date('Ymdhis',time()).rand(100,999).'.jpg';
                     $res=rename($value, $imgPath.$fileName);
                     $imgs[$key]='/'.$imgPath.$fileName;
                     $restr='';
                       if(false !==$res) {
                            $restr.='t';
                        }else{
                            $restr.='f';
                        }
                }

            }
            
            //将投票信息写入数据库
            $t_vote_item=M('vote_item');
            $t_vote_item->startTrans();//开启事务
            $item['fvip_key']=$fvip_key;
            $item['fvitem_imgs']=json_encode($imgs);
            $item['fvitem_xuanyan']=base64_encode(I('post.item_xuanyan','','htmlspecialchars'));
            $item['fvitem_bmtime']=time();
            $ress=$t_vote_item->add($item);

            if($ress>0&&strpos($restr,'f')===false){
                $t_vote_item->commit();
                $result['statu']='success';
                $result['msg']='报名成功';

                //统计报名人数并更新到
                $where['fvote_key']=$item['fvote_key'];
                $vitem_count=M('vote_item')->where($where)->count();
                M('vote')->where(array('fkey'=>$where['fvote_key']))->save(array('fvote_bm_count'=>$vitem_count));

                return json($result);
            }else{
                $t_vote_item->rollback();
                $result['statu']='forbidden';
                $result['msg']='报名失败';
                return json($result);
            }
        }
       /* 投票操作*/
        public function do_vote(){
            $fvitem_key=(int)I('post.fkey');
            $voteid=(int)I('post.voteid');
            $moban=(int)I('post.moban');
            $action=I('post.action');
            //插入投票记录表
            $data['fvip_key']=(int)session('user.user_id');
            $data['fvitem_key']=$fvitem_key;
            $data['fvote_key']=$voteid;

            //判断是否是会员
            
            $is_reg=is_reg(session('user.user_id'));
            $voteres=M('vote')->field('fvote_fsnub,fvote_tpnub,fvote_vipnub,fvote_enddate,fvote_statdate')->where(array('fkey'=>$voteid))->find();
            if($voteres['fvote_statdate']>time()){
                $ress['error']='zg_over';
                $ress['statu']='forbidden';
                $ress['msg']='活动尚未开始';
                        return json($ress);
            }
            if($voteres['fvote_enddate']<time()){
                $ress['error']='zg_over';
                $ress['statu']='forbidden';
                $ress['msg']='活动已经结束';
                        return json($ress);
            }
            if($is_reg=="no_subsribe"){
                    $ress['error']='no_subsribe';
                    $ress['statu']='forbidden';
                    if($voteres['fvote_tpnub']==0){
                        $ress['msg']='请先关注微信公众号';
                        return json($ress);
                    }elseif(empty($action)){
                        $ress['msg']='您还没关注我们公众号，去关注获得更多特权？';
                        return json($ress);
                    }else{
                        $gzcount=$voteres['fvote_tpnub'];
                    }
                    
                }
            if($is_reg=="no_reg"){
                    $ress['error']='no_reg';
                    $ress['statu']='forbidden';
                    if($voteres['fvote_fsnub']==0){
                        $ress['msg']='请先注册会员';
                        return json($ress);
                    }elseif(empty($action)){
                        $ress['msg']='您还没注册会员，去注册会员获取更多特权？';
                        return json($ress);
                    }else{
                         $gzcount=$voteres['fvote_fsnub'];
                    }
                    
                }
            if($is_reg=="have_reg"){
                    $ress['error']='have_reg';
                    $ress['statu']='forbidden';
                    if($voteres['fvote_vipnub']==0){
                        $ress['msg']='会员不能投票';
                        return json($ress);
                    }else{
                        $gzcount=$voteres['fvote_vipnub'];
                    }
                    
                }

            //检测投票次数是否达到上限
            //M('vote_remain')=M('vote_remain');
            $condii['fvip_key']=$data['fvip_key'];
            $condii['fvote_key']=$voteid;
            $remain=M('vote_remain')->where($condii)->find();
            $gzcount=($gzcount==null)?1:$gzcount;
            if(((int)$remain['fvote_give_count']+$gzcount-$remain['fvote_used_count'])<1 && $remain!=null){
                $ress['error']='zg_over';
                $ress['statu']='forbidden';
                $ress['msg']='您的投票资格次数已达上限';
            }else{
                
                $data['fcreate_time']=time();
                if($re=M('vote_record')->add($data)){
                    $ress['error']='success';
                    $ress['msg']='投票成功';
                    //统计投票总人数并更新到t_vote
                    $where['fvote_key']= $voteid;
                    $vrecord_count=M('vote_record')->where($where)->count();
                    M('vote')->where(array('fkey'=>$where['fvote_key']))->save(array('fvote_vote_count'=>$vrecord_count));
                    //统计投票人数
                    $condi['fvitem_key']=$fvitem_key;
                    $fvitem_count=M('vote_record')->where($condi)->count();
                    M('vote_item')->where(array('fkey'=>$fvitem_key))->save(array('fvitem_count'=>$fvitem_count));
                   /* 统计已经使用资格*/
                    $recount=M('vote_record')->where($condii)->count();
                    $udate['fvote_used_count']=$recount;
                    $udate['fupdate_time']=time();
                    if(is_array($remain)){
                        M('vote_remain')->where($condii)->save($udate);
                    }else{
                        $udate['fvip_key']=$data['fvip_key'];
                        $udate['fvote_key']=$voteid;
                        M('vote_remain')->add($udate);
                    }
                    
                }else{
                    $ress['error']='fail';
                    $ress['statu']='cancel';
                    $ress['msg']='投票失败';
                }
            }
            return json($ress);
            
            
    }
        //查询操作
        public function search(){
            if(IS_AJAX){
                $keyword=(string)I('post.keyword');
                $voteid=(int)I('post.voteid');
                $Vote_item = D('Voteitem');//实例化视图
                if (preg_match ("/^[1][0-9]{4}$/", $keyword)) { 
                    $keyword=substr($keyword, 1,strlen($keyword)-1);
                    $keyword=preg_replace('/^0+/','',$keyword);
                }else{
                    return json(array('statu'=>'error','msg'=>'编码输入有误'));
                    exit();
                }
                
               // $keyword=substr((string)$keyword, 1,size($keyword));
                //var_dump($keyword);
                $map['fvote_key']  = $voteid;
                $map['fkey']  = $keyword;
                $list=$Vote_item->where($map)->select();
                $htmlstr='';

                foreach ($list as $key => $value) {
                    if(is_base64($value['fvip_webcnickname']) ==true){
                        $fvip_webcnickname=base64_decode($value["fvip_webcnickname"]);

                    }else{
                        $fvip_webcnickname=$value["fvip_webcnickname"];
                    }
                    if(is_base64($value['fvitem_xuanyan']) ==true){
                        $fvitem_xuanyan=base64_decode($value["fvitem_xuanyan"]);
                        
                    }else{
                        $fvitem_xuanyan=$value["fvitem_xuanyan"];
                    }
                    $wximg=json_decode($value['fvitem_imgs']);
                    $wximgstr=implode(';',$wximg);
                    $fvitem_count=($value["fvitem_count"]==null)?0:$value["fvitem_count"];
                    
                    $htmlstr.='<li class="item"><div class="box"><img src="'.$wximg[0].'" all-img="'.$wximgstr.'"><div class="info"><span>'.$fvip_webcnickname.'</span><span class="votecount">'.$fvitem_count.'票</span></div><div>NO.1'.sprintf("%04s", $value["fkey"]).'</div><span class="btn do_vote" data="'.$value["fkey"].'">立即投票</span></div><input type="hidden" name="xuanyan" value="'.$fvitem_xuanyan.'"/>';
                }
                $htmlstr.='<input type="hidden" name="order" value="'.$order.'"></li>';
                $ress['page']=$show;
                $ress['htmlstr']=$htmlstr;
                echo $htmlstr.'|'.$show;
            }
        }

        /*分享后奖励投票资格*/
        public function addvote_allowint(){
            if(IS_AJAX){
                $voteid=I('post.voteid');
                $type=I('post.type');
                $condii['fvip_key']=(int)session('user.user_id');
                $condii['fvote_key']=(int)$voteid;

                $give_count=M('vote')->where(array('fkey'=>$voteid))->getField('fvote_give_count');
                if($give_count==null||$give_count==0){
                    exit();
                }

                //$t_vote_remain=M('vote_remain');
                $remain=M('vote_remain')->where($condii)->find();
                $data['fupdate_time']=time();
                $data['fvote_give_time']=time();
                $data['fvote_give_count']=$give_count;
                if(is_array($remain)){
                    if($type=='ShareAppMessage'){
                        if($remain['fvote_give_count']>0&&$remain['fvote_give_count']!=null){
                            $ress['statu']='have_give';
                            return json($ress);
                            exit();
                        }
                    }else{
                        if($remain['fvote_give_time']>=strtotime(date('Y-m-d 0:0:0'))){
                            exit();
                        }
                    }

                    $data['fvote_give_count']=$remain['fvote_give_count']+$give_count;
                    $res=M('vote_remain')->where($condii)->save($data);
                    
                }else{
                    $data['fvip_key']=$condii['fvip_key'];
                    $data['fvote_key']=$voteid;
                    $res=M('vote_remain')->add($data);
                }
                if($res>0&&$give_count>0){
                    $ress['statu']='success';
                    $ress['msg']='恭喜您！获得'.$give_count.'次投票机会';
                }
                return json($ress);
            }
            
        }

        public function getwxsubscribeurl(){
            $dltoken=I('post.dltoken');
            $wxsubscribe_url=M('wx_user')->where(array('appid'=>$dltoken))->getField('wx_subscribe_gdurl');
             $arr['statu']='success';
             $arr['value']=$wxsubscribe_url;
             return json($arr);

        }

       

            //根据微信服务器serverid获取图片地址
        public function getwxpic(){
            $media_id=I('post.media_id');
            $res='fail';
            $jssdk = new \Org\Wejssdk\Jssdk(C('WX_APPID'), C('WX_APPSERCT'));
            $accessToken = $jssdk->getAccessToken();
            $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$accessToken&media_id=$media_id";
            //用curl请求，返回文件资源和curl句柄的信息
            $info = $this->httpGet($url);
            //图片文件名
            $tmp_path=C('TMP_PATH');
            if(!isset($tmp_path)){
                $tmp_path='Public/tmp/';//定义临时目录，所有上传图片临时存放
                C('TMP_PATH',$tmp_path);
            }
            $fileName = date('Ymdhis',time()).rand(100,999).'.jpg';
           
            $path = $tmp_path.$fileName;

            //将资源写入文件里
            if ($this->saveFile($path, $info)) {
               $res=$path;
            }
            echo $res;
        }


        private function httpGet($url) {
          $curl = curl_init();
          curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($curl, CURLOPT_TIMEOUT, 500);
          // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
          // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
          curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
          curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
          curl_setopt($curl, CURLOPT_URL, $url);

          $res = curl_exec($curl);
          curl_close($curl);

          return $res;
        }

        /**
              * 将资源写入文件
              * @param  string 资源uri
              * @param  source 资源
              * @return boolean 
        */
             private function saveFile($path, $fileContent) {
                 $fp = fopen($path, 'w');
                       if (false !== fwrite($fp, $fileContent)) {
                           fclose($fp);
                           return true;
                       }
                   
                   return false;
               }

        //统计投票浏览量
        public function tongji_vote(){
            //$t_vote_scan=M('vote_scan');

            $data['fvote_key']=I('post.voteid');
            $data['fsub_vipkey']=I('post.sub_fvipkey');
            $data['fscan_source_type']=I('post.scan_type');
            $data['fscan_source_appid']=I('post.dltoken');
            $data['fscan_source_url']=I('post.fromuri');
            $data['fvip_key']=session('user.user_id');
            //生成唯一标识码
            $data['fscan_sign']=md5(json_encode($data));
            $data['fscan_time']=time();
            //按分钟为统计单位
            if(cookie('fscan_sign')){
                if(cookie('fscan_sign')[0]==$data['fscan_sign']&&(time()<cookie('fscan_sign')[1]+60)){
                   exit();
                }
            }else{
                $ress=M('vote_scan')->field('fscan_time')->where(array('fscan_sign'=>$data['fscan_sign']))->order('fkey desc')->find();
                if($ress['fscan_time']+60>time()){
                    exit();
                }
            }
            if($res=M('vote_scan')->add($data)){
                cookie('fscan_sign',array($data['fscan_sign'],time()));
            }
           
            
        }
        //统计分享
        public function tongji_share(){
            $t_vote_share=M('vote_share');
            $data['fvote_key']=I('post.voteid');
            $data['fvip_key']=session('user.user_id');
            $data['fshare_area']=I('post.share_area');
            $data['fshare_appid']=I('post.dltoken');
            $data['fshare_time']=time();
            $t_vote_share->add($data);
        }
        //获取换装素材
        public function getmatter(){
            $type=I('post.type');
            $match=I('post.match');
            if(!empty($type)){
                $condi['fmatter_type']=$type;
            }
            if(!empty($match)){
                $condi['fmatch_top_name']=$match;
                //查询是否有内穿样式
                $styles=M('cdresse_matter')->where(array('fmatter_name'=>$match))->getField('fmatter_name2');
            }
            $ress=M('cdresse_matter')->where($condi)->select();
            if($styles) $ress[0]['style']=$styles;
            return json($ress);
            //return json($ress);
        }
        //保存搭配方案
        public function save_dapei(){
            if(IS_POST&&isset($_POST['img'])){
                $dpstr=I('post.dpstr');
                $img=I('post.img');
                $voteid=I('post.voteid');
                $image = base64_decode(substr($img, 22));
                header('Content-Type: image/png');
                $upload_file_url='public/seller/img/upload/';
                $file_path=$upload_file_url.date('ym',time());//根据年月分组
                $file_name=date('Ymdhis',time()).rand(100,999).'.jpg';//重命名
                  if(!file_exists($file_path)){
                    mkdir($file_path,0777,true);
                  }
                $fileurl=$file_path .'/'. $file_name;
                $fp = fopen($fileurl, 'w');
                fwrite($fp, $image);
                fclose($fp);

                $data['fmatch_style']=$dpstr;
                $data['fvip_key']=session('user.user_id');
                $data['fmatch_img']=$fileurl;
                $data['fmatch_dt']=time();
                $data['fvote_key']=$voteid;
                $t_cdresse_match=M('cdresse_match');
                $cdressres=$t_cdresse_match->add($data);

                if($cdressres){
                    $result['statu']='success';
                    $result['msg']='保存成功';
                }else{
                    $result['statu']='forbidden';
                    $result['msg']='保存失败';
                   
                }
                 return json($result);
               
            }
           
        }
        //删除搭配图片
         public function del_img(){
            if(IS_POST){
                $fkey=I('post.fkey');
                $res=M('cdresse_match')->where(array('fkey'=>$fkey))->delete();
                if($res){
                    echo 'success';
                }
            }
         }

         //统计商品分享
        public function tongji_goods_share(){
            $goods_share=M('goods_share');
            $data['user_id']=I('post.user_id');
            $data['goods_id']=I('post.goods_id');
            $data['share_ip']= getIP();
            $data['share_url']=I('post.share_url');
            $data['share_area']=I('post.share_area');
            $data['share_appid']=I('post.share_appid');
            $data['share_time']=time();
            $res=$goods_share->add($data);
            echo $res;
        }
         public function save_location(){
            $lat=I('post.lat');
            $lng=I('post.lng');
            $pickup_id=I('post.pickup_id');
           
            $res=M('pick_up')->where('pickup_id',$pickup_id)->save(['lat'=>$lat,'lng'=>$lng,'is_update'=>1]);
            if($res>0){
                echo 'success';
            }
           
         }

        
    }





